import { message, notification, Modal, Spin } from 'ant-design-vue'
import { createApp, h } from 'vue'

let instance = null

// 定义全屏遮罩样式
const style = {
  position: 'fixed',
  left: 0,
  top: 0,
  width: '100%',
  height: '100%',
  display: 'flex',
  justifyContent: 'center',
  alignItems: 'center',
  background: 'rgba(0, 0, 0, .5)',
  zIndex: 99999
}
function getInstance() {
  if (!instance) {
    const vn = createApp({
      data() {
        return {
          show: false,
          message: 'Loading...',
          timeoutId: 'loader'
        }
      },
      unmounted() {
        if (instance && instance.$el) {
          instance.$el.remove() // 当组件卸载时，从DOM中移除元素以避免内存泄漏
        }
      },
      methods: {
        loading(val, timeout) {
          this.show = true
          this.message = val || 'Loading...'
          if (timeout) {
            this.timeoutId = setTimeout(() => {
              this.close()
            }, timeout) // 超时时间单位为毫秒
          }
        },
        close() {
          clearTimeout(this.timeoutId) // 清除定时器
          this.show = false
        }
      },
      render() {
        return this.show ? h('div', { style }, [h(Spin, { tip: this.message })]) : null
      }
    })
    const ele = document.createElement('div')
    instance = vn.mount(ele)
    document.body.appendChild(ele)
  }
  return instance
}

export default {
  msg(content, duration = 3) {
    message.info(content, duration)
  },
  msgSuccess(content, duration = 3) {
    message.success(content, duration)
  },
  msgError(content, duration = 3) {
    message.error(content, duration)
  },
  msgWarning(content, duration = 3) {
    message.warning(content, duration)
  },
  openNotification(content, params = {}) {
    const type = params.type || 'info'
    notification[type]({
      message: params.title || '系统提示',
      description: content,
      duration: params.duration || 3,
      ...params
    })
  },
  /**
   * @param { String } content
   * @param { Object } params
   */
  confirm(content, params = {}) {
    return new Promise((resolve, reject) => {
      Modal.confirm({
        title: '提示',
        content: content || '',
        okText: params.okText || '确认',
        cancelText: params.cancelText || '取消',
        ...params,
        onOk() {
          resolve('confirm')
        },
        onCancel() {
          reject('cancel')
        }
      })
    })
  },
  loading(content) {
    getInstance().loading(content)
  },
  closeLoading() {
    getInstance().close()
  }
}
